package org.geektimes.serialize.impl;

import javax.cache.CacheException;
import java.io.*;

public class ObjectSerializer<T> extends AbstractSerializer<T> {
    /**
     * 序列化对象。将给定的对象序列化成字节数组
     *
     * @param value
     */
    @Override
    public byte[] doSerialize(T value) {
        byte[] bytes = null;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)
        ) {
            // Key -> byte[]
            objectOutputStream.writeObject(value);
            bytes = outputStream.toByteArray();
        } catch (IOException e) {
            throw new CacheException(e);
        }
        return bytes;
    }

    @Override
    public T doDescrialize(byte[] bytes, Class<T> typeClass) {
        if (bytes == null) {
            return null;
        }
        Object value = null;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
             ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)
        ) {
            // byte[] -> Value
            value = objectInputStream.readObject();
        } catch (Exception e) {
            throw new CacheException(e);
        }
        return (T) value;
    }


}
